route.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { ResultDto } from '@/types/response/common';
  3. import { fetchJson } from '@/lib/utils/server';
  4. function buildEndpoint(path?: string[]): string {
  5. const suffix = (path ?? []).join('/');
  6. return suffix ? `/api/forum/posts/${suffix}` : '/api/forum/posts';
  7. }
  8. async function forwardWithBody(request: NextRequest, endpoint: string, method: 'POST' | 'PUT'): Promise<ResultDto> {
  9. const contentType = request.headers.get('content-type') || '';
  10. if (contentType.includes('multipart/form-data')) {
  11. const form = await request.formData();
  12. return await fetchJson(endpoint, { method, body: form });
  13. }
  14. if (contentType.includes('application/json')) {
  15. const text = await request.text();
  16. return await fetchJson(endpoint, {
  17. method,
  18. body: text || undefined,
  19. headers: { 'Content-Type': 'application/json' }
  20. });
  21. }
  22. return await fetchJson(endpoint, {
  23. method,
  24. body: await request.arrayBuffer(),
  25. headers: contentType ? { 'Content-Type': contentType } : undefined
  26. });
  27. }
  28. export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  29. const { path } = await params;
  30. const endpoint = buildEndpoint(path);
  31. const url = new URL(request.url);
  32. const res: ResultDto = await fetchJson(`${endpoint}${url.search}`, { method: 'GET' });
  33. return NextResponse.json(res);
  34. }
  35. export async function POST(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  36. const { path } = await params;
  37. const endpoint = buildEndpoint(path);
  38. const res = await forwardWithBody(request, endpoint, 'POST');
  39. return NextResponse.json(res);
  40. }
  41. export async function PUT(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  42. const { path } = await params;
  43. const endpoint = buildEndpoint(path);
  44. const res = await forwardWithBody(request, endpoint, 'PUT');
  45. return NextResponse.json(res);
  46. }
  47. export async function DELETE(_: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  48. const { path } = await params;
  49. const endpoint = buildEndpoint(path);
  50. const res: ResultDto = await fetchJson(endpoint, { method: 'DELETE' });
  51. return NextResponse.json(res);
  52. }